const http = require("http");
const path = require("path");
const fs = require("fs");
const mime = require("mime");

const PORT = 8080;
const HOST = "http://localhost/";

const server = http.createServer((req, res) => {
  // 1 路径处理
  const url = new URL(req.url, HOST);
  let pathname = url.pathname;
  pathname = decodeURIComponent(req.url);
  let absPath = path.join(__dirname, pathname);
  // 2 目标资源状态处理
  fs.stat(absPath, (err, statObj) => {
    if (err) {
      res.statusCode = 404;
      res.end("Not Found");
      return;
    }
    if (statObj.isFile()) {
      // 此时说明路径对应的目标是一个文件，可以直接读取然后回写
      fs.readFile(absPath, (err, data) => {
        res.setHeader("Content-type", mime.getType(absPath) + ";charset=utf-8");
        res.end(data);
      });
    } else {
      // 此时非文件则为目录
      fs.readFile(path.join(absPath, "index.html"), (err, data) => {
        res.setHeader("Content-type", mime.getType(absPath) + ";charset=utf-8");
        res.end(data);
      });
    }
  });
});
server.listen(PORT, () => {
  console.log("server is listening on port " + PORT);
});
